<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}替代料`">
    <template #header>
      <h4>{{ drawerProps.title }}替代料</h4>
    </template>
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="MBOM项ID" prop="mbomItemId">
        <el-input-number 
          v-model="drawerProps.row.mbomItemId" 
          placeholder="请输入MBOM项ID" 
          :min="1" 
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="替代料物料ID" prop="substituteMaterialId">
        <el-input-number 
          v-model="drawerProps.row.substituteMaterialId" 
          placeholder="请输入替代料物料ID" 
          :min="1" 
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="替代比例" prop="substituteRatio">
        <el-input-number
          v-model="drawerProps.row.substituteRatio"
          placeholder="请输入替代比例"
          :min="0"
          :max="100"
          :precision="2"
          style="width: 100%"
        />
        <span style="margin-left: 8px; color: #909399;">%</span>
      </el-form-item>

      <el-form-item label="优先级" prop="priority">
        <el-input-number
          v-model="drawerProps.row.priority"
          placeholder="请输入优先级"
          :min="1"
          :max="999"
          style="width: 100%"
        />
        <div style="margin-top: 4px; color: #909399; font-size: 12px;">
          数值越小优先级越高
        </div>
      </el-form-item>

      <el-form-item label="有效期开始" prop="validFrom">
        <el-date-picker
          v-model="drawerProps.row.validFrom"
          type="datetime"
          placeholder="请选择有效期开始时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="有效期结束" prop="validTo">
        <el-date-picker
          v-model="drawerProps.row.validTo"
          type="datetime"
          placeholder="请选择有效期结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="drawerProps.row.remark"
          placeholder="请输入备注信息"
          type="textarea"
          :rows="3"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="SubstituteMaterialDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { SubstituteMaterial } from "@/api/modules/substituteMaterial";

const rules = reactive({
  mbomItemId: [{ required: true, message: "请输入MBOM项ID" }],
  substituteMaterialId: [{ required: true, message: "请输入替代料物料ID" }],
  substituteRatio: [
    { required: true, message: "请输入替代比例" },
    { type: "number", min: 0, max: 100, message: "替代比例必须在0-100之间" }
  ],
  priority: [
    { required: true, message: "请输入优先级" },
    { type: "number", min: 1, message: "优先级必须大于0" }
  ]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<SubstituteMaterial.ViewEntity & SubstituteMaterial.AddRequest>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    
    // 验证有效期
    if (drawerProps.value.row.validFrom && drawerProps.value.row.validTo) {
      const validFrom = new Date(drawerProps.value.row.validFrom);
      const validTo = new Date(drawerProps.value.row.validTo);
      if (validFrom >= validTo) {
        ElMessage.error("有效期开始时间必须早于结束时间");
        return;
      }
    }
    
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}替代料成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.error(error);
      ElMessage.error({ message: `${drawerProps.value.title}替代料失败！` });
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style scoped>
:deep(.el-form-item__label) {
  font-weight: 600;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>